import React, { useState, useEffect, useRef } from 'react';

const add = (props: any) => {
  const contentIFrameRef = useRef<HTMLIFrameElement>(null);
  const [url, setUrl] = useState('');

  useEffect(() => {
    const { id } = props.location.query;
    setUrl(
      () => `${window.apiPrefixUri || ''}/workflow/api/html/index.html#/editor/${id}`,
    );
    const iframe: HTMLIFrameElement | null = contentIFrameRef.current;
    if (iframe && iframe.contentWindow) {
      const iframeDocument = iframe.contentWindow.document;
      // 写入内容（这里举例的 iframe 内容是请求接口后返回 html，也就是 res，比如 res="<h1>标题</h1>"）
      // 如果需要 css，写入 css，此处的 css 是写在根目录里（与 index.html 同级）
      if (!iframeDocument.getElementsByTagName('link')[0]) {
        const link = iframeDocument.createElement('link');
        link.rel = 'stylesheet';
        link.type = 'text/css';
        iframeDocument.head.appendChild(link);
      }
    }
  }, []);
  return (
    <div style={{ overflow: 'hidden', height: '100%' }}>
      <iframe
        ref={contentIFrameRef}
        title="iframe"
        sandbox="allow-same-origin allow-scripts allow-popups allow-forms"
        scrolling="hidden"
        style={{ border: 0, height: '100%', width: '100%' }}
        src={url}
      />
    </div>
  );
};

export default add;
